<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>

<body>
    <input type="text">
    <button id="btnSend">发送请求</button>
    <button id="btnCancel">取消请求</button>

    <script>
        const oIpt = document.querySelector("input")
        const btnSend = document.getElementById("btnSend")
        const btnCancel = document.getElementById("btnCancel")
        const CancelToken = axios.CancelToken
        let cancel = null

        //创建axios的实例
        const myAxios = axios.create({
            baseURL: "/",
            timeout: 10000,
            headers: {}
        })
        // 给axios的实例添加拦截
        myAxios.interceptors.request.use(config => {
            //添加token
            const token = "afgaddaaw,gfasfhaus,jmijgishas"
            config.headers.token = token


            return config
        })

        //绑定点击事件
        btnSend.onclick = async function () {
            const iptData = oIpt.value
            try {
                const re = await myAxios.get("/user-delay", {
                    params: {
                        userId: iptData
                    },
                    cancelToken: new CancelToken(c => {
                        cancel = c
                    })

                })
            } catch (e) {
                console.log(e);
            }
        }

        // 绑定点击取消
        btnCancel.onclick = function () {
            cancel()
        }
    </script>
</body>

</html>